package com.xz.video.service.impl;

import com.xz.video.entity.vo.UserLastMsgVo;
import com.xz.video.service.MessageService;
import com.xz.video.service.SseEmitterService;
import com.xz.video.service.UserMessageCountService;
import io.renren.common.exception.RenException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service("sseEmitterService")
@Slf4j
public class SseEmitterServiceImpl implements SseEmitterService {

    @Autowired
    UserMessageCountService userMessageCountService;
    /**
     * 容器，保存连接，用于输出返回
     */
    private static Map<String, SseEmitter> sseCache = new ConcurrentHashMap<>();


    @Override
    public SseEmitter createSseConnect(String clientId) {
        // 设置超时时间，0表示不过期。默认30000毫秒
        //可以在客户端一直断网、直接关闭页面但未提醒后端的情况下，服务端在一定时间等待后自动关闭网络连接
        SseEmitter sseEmitter = new SseEmitter(0L);
        sseCache.put(clientId, sseEmitter);
        log.info("sse连接，当前客户端：{}", clientId);
        pushMessage(clientId);
        return sseEmitter;
    }

    @Override
    public void closeSseConnect(String clientId) {
        SseEmitter sseEmitter = sseCache.get(clientId);
        if (sseEmitter != null) {
            sseEmitter.complete();
            sseCache.remove(clientId);
        }
    }

    @Override
    public void pushMessage(String clientId) {
        try {
            SseEmitter sseEmitter = sseCache.get(clientId);
            Map<String, Object> userNoReplyCount= userMessageCountService.getUserNoReplyCount(clientId);
            sseEmitter.send(
                    SseEmitter
                            .event()
                            .data(userNoReplyCount)
                            .reconnectTime(3000)
            );
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

}
